# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################

import os, sys

dir_path = os.path.dirname(os.path.realpath(__file__))
parent_dir_path = os.path.abspath(os.path.join(dir_path, os.pardir))
sys.path.insert(0, parent_dir_path)
from flask import Blueprint
from flask import request
from payapi import paycommon
import utils.common.log as log
import utils.common.httpclient as httpclient
import random
import time
import datetime
import threading
import hashlib
import requests
import json
import uuid
import utils.pgsql.pgvlogrecord as record
import utils.pgsql.pgtechpay as pgtechpay
import utils.pgsql.pgpay as pgpay
import utils.pgsql.pgtechpayflow as pgtechpayflow
import utils.pgsql.pgchannel as pgchannel
import utils.message.response as response
from utils.common.func import time_data
from utils.wraps import token, urlcost
import redis
import utils.pgsql.pgadmin as pgadmin

# 创建一个蓝图
tech_module = Blueprint("tech", __name__, url_prefix="/payapi/tech/pay")

# Receive the order records pushed by the applet
# 接收小程序推送的订单记录

@tech_module.route("/paymentsave", methods=["POST"])
def paymentsave():
    Info = json.loads(request.data)
    # 
    now = datetime.datetime.now()
    now1 = datetime.date(
        now.year,
        now.month,
        now.day,
    )

    # # to algorithm
    # status,ret_algo = httpclient.post_weixin_paydata(Info)
    # if status :
    #     log.logging.info("post_weixin_paydata success : {} ;;{}".format(ret_algo,Info))
    # else :
    #     log.logging.info("post_weixin_paydata failed : {} ; {}".format(ret_algo,Info))

    obj = pgtechpay.Pgtechpay()
    ret = obj.addpay(Info)   # 插 tbl_techpay 库
    log.logging.info("Pay Info : {}  ; ret : {} ".format(Info, ret))

    if ret:
        return response.make_response_success_no_data()
    else:
        return response.make_response_1000()

def deviation_date(date, offsets):
    start_date = datetime.datetime.strptime(date, "%Y-%m-%d")
    now_date = datetime.timedelta(days=offsets)
    a = start_date + now_date
    return a.strftime("%Y-%m-%d")


@tech_module.route("/chanorderList", methods=["POST"])
def chanorderList():
    Info = json.loads(request.data)
    startTime = ""
    endTime = ""
    if Info["time"]:
        startTime = Info["time"][0]
        endTime = Info["time"][1]
    else:
        startTime = "1976-01-01"
        endTime = time.strftime("%Y-%m-%d", time.localtime())
    
    obj = pgtechpay.Pgtechpay()
    ret = obj.chantechpay(
        Info["chan"],
        Info["pageNo"],
        Info["pageSize"],
        startTime,
        endTime
    )
    
    # end_date = Info[1][1]
    # begin_date = Info[1][0]
    # obj = pgpay.PgPay()
    # ret = obj.chanpay(
    #     Info[0],
    #     datetime.datetime.strptime(begin_date, "%Y-%m-%d"),
    #     datetime.datetime.strptime(deviation_date(end_date, +1), "%Y-%m-%d"),
    # )
    # log.logging.info("ret:{}".format(ret))

    return response.make_response_success(ret)


@tech_module.route("/myinfo", methods=["POST","GET"])
# @token.login_required
@urlcost.cost_count_wraps
def my_info():
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    log.logging.info("token:{}".format(request.headers["Authorization"]))
    log.logging.info("userInfo:{}".format(userInfo))
    cache = redis.Redis(host='10.206.0.115', port=6379, db=10, password='SKadmin123_456')
    t1 = cache.get(request.headers["Authorization"])  # b'929'
    limit = ""
    if t1:
        admin_id = int(t1)
        obj = pgadmin.PgAdmin()
        user_dic = obj.get(admin_id)
        limit = user_dic['playground_limit']
        log.logging.info(admin_id)
        log.logging.info(user_dic)
    return response.make_response_success({"admin_id":admin_id, "limit":limit,"userInfo":userInfo,"token":request.headers["Authorization"]})

    
@tech_module.route("/orderList", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def orderList():
    """input param :
    {
        "pageNo": 1 ,
        "pageSize": 10 ,
        "channelInfo":"xxx",
        "caseId":"0",
        "operatorId":"1",
        "startTime":16xxxx,
        "endTime":16xxxxx
    }
    """
    # userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    # playground_limit = userInfo['playground_limit'] if userInfo["role"] == 3 else ""
    cache = redis.Redis(host='10.206.0.115', port=6379, db=10, password='SKadmin123_456')
    t1 = cache.get(request.headers["Authorization"])
    playground_limit = ""
    grant_date = ''
    user_dic = {}
    if t1:
        admin_id = int(t1)
        obj = pgadmin.PgAdmin()
        user_dic = obj.get(admin_id)
        playground_limit = user_dic['playground_limit']
        if user_dic["role"] == 6:
            grant_date = record.PgRecord().get_grant_date(user_dic['adminId'])
    dic = json.loads(request.data)
    channelInfo = ""
    startTime = ""
    endTime = ""
    if "startTime" in dic and "endTime" in dic:
        startTime = time_data(dic["startTime"])
        endTime = datetime.datetime.strptime(deviation_date(time_data(dic["endTime"]), +1), "%Y-%m-%d")
    elif "piked_date" in dic and dic['piked_date']:
        startTime = f'{dic["piked_date"][0]} 00:00:00'
        endTime = f'{dic["piked_date"][1]} 23:59:59'
    else:
        startTime = "1976-01-01" if not grant_date else f'{grant_date} 00:00:00'
        endTime_str = time.strftime("%Y-%m-%d", time.localtime())
        endTime = datetime.datetime.strptime(deviation_date(endTime_str, +1), "%Y-%m-%d")

    if "playground_limit" in dic:
        playground_limit = dic['playground_limit']
    # if "channelInfo" in dic:
    #     channelInfo = "%" + dic["channelInfo"] + "%"
    if "adminId" not in dic :
        dic["adminId"] =  "-1"

    if "channelInfo" in dic :
        if dic["channelInfo"] !="" :
            channelInfo = "%" + dic["channelInfo"] + "%"

    if "operatorId" in dic:
        operatorId = dic["operatorId"]
    else:
        operatorId = "1"
    if operatorId == "1": 
        obj = pgtechpay.Pgtechpay()
    else:
        obj = pgtechpay.Pgtechpay()
    orderList = []
    order_status = None
    # 订单filter 退款
    if "order_status" in dic:
        if dic['order_status'] in ["success", "refund"]:
            order_status = dic['order_status']
    if "caseId" in dic:
        orderList = obj.PagetechCase(dic["caseId"],dic["pageNo"],dic["pageSize"],startTime,endTime,order_status,
                                     limit=playground_limit)
    else:
        if user_dic and int(user_dic["adminId"]) == 1:
            orderList = obj.PagetechAll( dic["pageNo"], dic["pageSize"], startTime, endTime,order_status=order_status)
        elif user_dic and int(user_dic["adminId"]) in [7,1367]:# shuikewenhua 账号;1367 财务
            orderList = obj.PagetechAll(dic["pageNo"], dic["pageSize"], startTime, endTime, order_status=order_status)
    log.logging.info("orderList:{}".format(orderList))
    # if orderList == "":
    #     return response.make_response_1505()
    # 新增商户ID转商户名功能
    mch ={
        1604603809:"浙江水科",
        1641930469:"AI视频",
        1598721581:"颖食严选"
    }
    for st in orderList:
        if "mch_id" in st:
            st['mch_name'] = mch[st['mch_id']]
    return response.make_response_success(orderList)

# def orderList():
#     """ input param :
#     {
#         "pageNo": 1 ,
#         "pageSize": 10 ,
#         "channelInfo":"xxx",
#         "caseId":"0",
#         "startTime":16xxxx,
#         "endTime":16xxxxx
#     }
#     """
#     dic = json.loads(request.data)
#     channelInfo = ""
#     startTime = ""
#     endTime = ""
#     if "startTime" in dic and "endTime" in dic:
#         startTime = time_data(dic["startTime"])
#         endTime = time_data(dic["endTime"])
#     else:
#         startTime = "1976-01-01"
#         endTime = time.strftime("%Y-%m-%d", time.localtime())

#     # print("startTime : {} ".format(startTime))
#     # print("endTime : {} ".format(endTime))

#     if "channelInfo" in dic:
#         channelInfo = "%" + dic["channelInfo"] + "%"

#     # print("channelInfo : {}".format(channelInfo))

#     obj = pgtechpayflow.Pgtechpayflow()
#     orderList = ""

#     if "caseId" in dic:
#         orderList = obj.PageCase(
#             dic["caseId"],
#             channelInfo,
#             dic["pageNo"],
#             dic["pageSize"],
#             startTime,
#             endTime,
#         )
#     else:
#         orderList = obj.PageAll(
#             channelInfo, dic["pageNo"], dic["pageSize"], startTime, endTime
#         )
#     print(orderList)
#     if orderList == "":
#         return response.make_response_1505()
#     return response.make_response_success(orderList)


@tech_module.route("/paydevide", methods=["POST"])
def paydevide():
    dic = json.loads(request.data)
    day_value = dic["day_value"]
    pay = pgtechpay.Pgtechpay()
    payflow = pgtechpayflow.Pgtechpayflow()
    paycommon.devidedinto_pay(pay, payflow, day_value)
    obj_payflow = pgtechpayflow.Pgtechpayflow()
    today_pay = obj_payflow.GetAllTodayList(datetime.date.today())
    return response.make_response_success(today_pay)


def _time_devidedinto_task():

    while True:
        if datetime.datetime.now().hour == 2:  # 获取当前时间 小时数
            time.sleep(3)
            pay = pgtechpay.Pgtechpay()
            payflow = pgtechpayflow.Pgtechpayflow()
            paycommon.devidedinto_pay(pay, payflow, -1)
            time.sleep(4000)
        else:
            time.sleep(3500)



t1 = threading.Thread(target=_time_devidedinto_task, daemon=True)
t1.start()

if __name__ == "__main__":

    ### XXXXX
    pay = pgtechpay.Pgtechpay()
    payflow = pgtechpayflow.Pgtechpayflow()
    paycommon.devidedinto_pay(pay, payflow, -1)
    print("tech test : @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
